package com.ruoyi.system.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.constant.UserConstants;
import com.ruoyi.common.core.exception.ServiceException;
import com.ruoyi.common.core.utils.SpringUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.system.api.RemoteStoreService;
import com.ruoyi.system.api.domain.SysRole;
import com.ruoyi.system.api.domain.SysUser;
import com.ruoyi.system.domain.SysUserPost;
import com.ruoyi.system.domain.SysUserRole;
import com.ruoyi.system.mapper.UserMapper;
import com.ruoyi.system.mapper.UserPostMapper;
import com.ruoyi.system.mapper.UserRoleMapper;
import com.ruoyi.system.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, SysUser> implements UserService {
    @Autowired
    private UserPostMapper userPostMapper;

    @Autowired
    private UserRoleMapper userRoleMapper;

    @Autowired
    private RemoteStoreService remoteStoreService;

    @Override
    public List<SysUser> selectUserList(IPage<SysUser> page, SysUser user) {
        return baseMapper.selectUserList(page,user);
    }

    @Override
    public boolean checkUserNameUnique(SysUser user) {
        Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
        SysUser sysUser = baseMapper.selectOne(
                Wrappers.<SysUser>lambdaQuery()
                .select(SysUser::getUserId,SysUser::getUserName)
                .eq(SysUser::getUserName, user.getUserName())
                .eq(SysUser::getDelFlag, "0"));
        if (StringUtils.isNotNull(sysUser) && sysUser.getUserId().longValue() != userId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    @Override
    public boolean checkPhoneUnique(SysUser user) {
        Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
        SysUser sysUser = baseMapper.selectOne(
                Wrappers.<SysUser>lambdaQuery()
                        .select(SysUser::getUserId,SysUser::getPhonenumber)
                        .eq(SysUser::getPhonenumber, user.getPhonenumber())
                        .eq(SysUser::getDelFlag, "0"));
        if (StringUtils.isNotNull(sysUser) && sysUser.getUserId().longValue() != userId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    @Override
    public boolean checkEmailUnique(SysUser user) {
        Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
        SysUser sysUser = baseMapper.selectOne(
                Wrappers.<SysUser>lambdaQuery()
                        .select(SysUser::getUserId,SysUser::getEmail)
                        .eq(SysUser::getEmail, user.getEmail())
                        .eq(SysUser::getDelFlag, "0"));
        if (StringUtils.isNotNull(sysUser) && sysUser.getUserId().longValue() != userId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    @Override
    public void checkUserDataScope(Long userId) {
        if (!SysUser.isAdmin(SecurityUtils.getUserId()))
        {
            SysUser user = new SysUser();
            user.setUserId(userId);
            Page<SysUser> page = new Page<>();
            List<SysUser> users = baseMapper.selectUserList(page,user);
            if (StringUtils.isEmpty(users))
            {
                throw new ServiceException("没有权限访问用户数据！");
            }
        }
    }

    @Override
    public SysUser selectUserById(Long userId) {
        return baseMapper.selectUserById(userId);
    }

    @Override
    public int insertUser(SysUser user) {
        // 新增用户信息
        remoteStoreService.updateStoreUserIds(user.getUserId(),user.getStoreIds());
        // 新增用户岗位关联
        insertUserPost(user);
        // 新增用户与角色管理
        insertUserRole(user.getUserId(),user.getRoleIds());
        return 1;
    }

    @Override
    public void checkUserAllowed(SysUser user) {
        if (StringUtils.isNotNull(user.getUserId()) && user.isAdmin())
        {
            throw new ServiceException("不允许操作超级管理员用户");
        }
    }

    @Override
    public int updateUser(SysUser user) {
        Long userId = user.getUserId();
        // 删除用户与角色关联
        userRoleMapper.delete(Wrappers.<SysUserRole>lambdaQuery().eq(SysUserRole::getUserId,userId));
        // 新增用户与角色管理
        insertUserRole(user.getUserId(),user.getRoleIds());
        // 删除用户与岗位关联
        userPostMapper.delete(Wrappers.<SysUserPost>lambdaQuery().eq(SysUserPost::getUserId,userId));
        // 新增用户与岗位管理
        insertUserPost(user);
        remoteStoreService.updateStoreUserIds(user.getUserId(),user.getStoreIds());
        return baseMapper.updateById(user);
    }

    @Override
    public Long[] selectStoreIds(Long userId) {
        return remoteStoreService.selectStoreIds(userId);
    }

    @Override
    public List<Map<String, Object>> getPostData() {
        return baseMapper.getPostData(SecurityUtils.getUserId());
    }

    /**
     * 新增用户岗位信息
     *
     * @param user 用户对象
     */
    public void insertUserPost(SysUser user)
    {
        Long[] posts = user.getPostIds();
        if (StringUtils.isNotEmpty(posts))
        {
            // 新增用户与岗位管理
            List<SysUserPost> list = new ArrayList<SysUserPost>();
            for (Long postId : posts)
            {
                SysUserPost up = new SysUserPost();
                up.setUserId(user.getUserId());
                up.setPostId(postId);
                list.add(up);
            }
            userPostMapper.batchUserPost(list);
        }
    }

    /**
     * 新增用户角色信息
     *
     * @param userId 用户ID
     * @param roleIds 角色组
     */
    public void insertUserRole(Long userId, Long[] roleIds)
    {
        if (StringUtils.isNotEmpty(roleIds))
        {
            // 新增用户与角色管理
            List<SysUserRole> list = new ArrayList<SysUserRole>();
            for (Long roleId : roleIds)
            {
                SysUserRole ur = new SysUserRole();
                ur.setUserId(userId);
                ur.setRoleId(roleId);
                list.add(ur);
            }
            userRoleMapper.batchUserRole(list);
        }
    }
}
